package com.lr.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * .
 * Created by li.rui on 2017-07-10.
 */
@ServerEndpoint(value = "/ws")
@Component
@Slf4j
public class WebSocketServer {

    private Session session;
    private String name;
    private static Map<String,Session> users = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(final Session session){
        users.putIfAbsent(session.getId(),session);
        this.name = session.getRequestParameterMap().get("name").get(0);
        System.out.println(name + ", open..");
        this.session = session;
        this.session.setMaxIdleTimeout(50 * 1000);
        sendMessage("上线了...");
    }

    @OnMessage
    public void onMessage(String message,Session session){
        log.info(session.getUserProperties().toString());
        sendMessage(message);

    }

    @OnError
    public void onError(Session session, Throwable error) throws IOException {
        if(session.isOpen()) session.close();
        users.remove(session.getId());
        log.error("发生错误" + error.getMessage());
    }

    @OnClose
    public void OnClose(Session session) throws IOException {
        if(session.isOpen()) session.close();
        users.remove(session.getId());
        System.out.println("ws close。。。。");
    }




    public void sendMessage(String message) {
        users.forEach((key,s) -> {
            try {
                s.getBasicRemote().sendText(name +" : " + message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }


}
